package com.example.yamba;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;

import com.sina.weibo.sdk.openapi.models.Status;

/**
 * Created by jagery on 9/3/15.
 */
public class YambaWidget extends AppWidgetProvider {
    private static final String TAG = YambaWidget.class.getSimpleName();

    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){
        Cursor c = context.getContentResolver().query(StatusProvider.CONTENT_URi,null,null,null,null);
        Log.i(TAG,"get Cursor "+c);
        try{
            if(c.moveToFirst()){
                String json = c.getString(c.getColumnIndex(StatusData.C_STATUS));
                Status status = Status.parse(json);
                for(int appWidgetID : appWidgetIds){
                    Log.d(TAG, "Updating widget " + appWidgetID);
                    RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.yamba_widget);
                    views.setTextViewText(R.id.textUser,status.user.screen_name);
                    views.setTextViewText(R.id.textCreateAt,status.created_at);
                    views.setTextViewText(R.id.text,status.text);
                    views.setOnClickPendingIntent(R.id.yamba_icon, PendingIntent
                            .getActivity(context, 0, new Intent(context,
                                    TimelineActivity.class), 0));
                    appWidgetManager.updateAppWidget(appWidgetID, views);
                }
            }
        }finally{
            if(c!=null)
                c.close();
        }
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        super.onReceive(context, intent);
        if (intent.getAction().equals("com.example.yamba.NEW_STATUS")) {
            Log.d(TAG, "onReceived detected new status update");
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            this.onUpdate(context, appWidgetManager, appWidgetManager
                    .getAppWidgetIds(new ComponentName(context, YambaWidget.class)));
        }
    }
}
